#include "starmusic.h"
#include "ui_starmusic.h"

StarMusic::StarMusic(QWidget *parent)
    : QWidget(parent)
    , ui(new Ui::StarMusic)
    ,currentIndex(-1)
{
    ui->setupUi(this);

    initUi();
    initSqlite();

    initMusicList();
    initPlayer();
    connectSignalAndSlots();


}

StarMusic::~StarMusic()
{
    delete ui;
}

void StarMusic::initUi()
{
    this->setWindowFlag(Qt::FramelessWindowHint);

    // 设置窗口背景透明
    this->setAttribute(Qt::WA_TranslucentBackground);
    setWindowIcon(QIcon(":/images/star.png"));

    // 添加系统托盘 添加菜单如退出程序
    QSystemTrayIcon* trayIcon = new QSystemTrayIcon(this);
    trayIcon->setIcon(QIcon(":/images/star.png"));
    trayIcon->show();
    QMenu* trayMenu = new QMenu();
    trayMenu->addAction("显示",this,&QWidget::showNormal);
    trayMenu->addAction("退出",this,&StarMusic::starMusicQuit);
    trayIcon->setContextMenu(trayMenu);

    // 给窗口设置阴影效果
    QGraphicsDropShadowEffect* shadowEffect = new QGraphicsDropShadowEffect(this);
    shadowEffect->setOffset(0,0);
    shadowEffect->setColor("#000000");
    shadowEffect->setBlurRadius(10);
    this->setGraphicsEffect(shadowEffect);

    // 设置BtForm图标和文本信息
    ui->Rec->setIconandText(":/images/rec.png","推荐",0);
    ui->audio->setIconandText(":/images/radio.png","电台",1);
    ui->music->setIconandText(":/images/music.png","音乐馆",2);
    ui->like->setIconandText(":/images/like.png","我喜欢",3);
    ui->local->setIconandText(":/images/local.png","本地下载",4);
    ui->recent->setIconandText(":/images/recent.png","最近播放",5);

//    ui->local->showAnimal();
    ui->stackedWidget->setCurrentIndex(4);
    currentPage = ui->localPage;
    ui->local->FirstShow(true);
    // 随机种子 初始化推荐页面
    srand(time(NULL));
    ui->recMusicBox->initRecBoxUi(randomPiction(),1);
    ui->supplyMusicBox->initRecBoxUi(randomPiction(),2);

    // 设置CommonPage的信息
//    ui->likePage->setMusicListType(PageType::LIKE_PAGE);
    ui->likePage->setCommonPageUI("我喜欢",":/images/like.png");

//    ui->localPage->setMusicListType(PageType::LOCAL_PAGE);
    ui->localPage->setCommonPageUI("本地音乐",":/images/add.png");

//    ui->recentPage->setMusicListType(PageType::HISTORY_PAGE);
    ui->recentPage->setCommonPageUI("最近播放",":/images/music.png");

    // 播放控制区按钮图标设定
    ui->Play->setIcon(QIcon(":/images/play_2.png"));
    ui->playMode->setIcon(QIcon(":/images/shuffle_2.png"));
    volumetool = new VolumeTool(this);
    // 歌词对象
    lrcPage = new LrcPage(this);
    lrcPage->setGeometry(10,10,lrcPage->width(),lrcPage->height());
    lrcPage->hide();

    // 初始化动画对象
    lrcPageAnimal = new QPropertyAnimation(lrcPage,"geometry",this);
    lrcPageAnimal->setDuration(500); // 时间
    lrcPageAnimal->setStartValue(QRect(10,10+lrcPage->height(),lrcPage->width(),lrcPage->height()));
    lrcPageAnimal->setEndValue(QRect(10,10,lrcPage->width(),lrcPage->height()));
    ui->max->setEnabled(false);
}

void StarMusic::initPlayer()
{

    //1. 初始化媒体播放相关类对象
    player = new QMediaPlayer(this);
    playList = new QMediaPlaylist(this);
    //2. 设置播放模式
    playList->setPlaybackMode(QMediaPlaylist::Loop);
    //3. 播放列表设置到播放媒体对象中
    player->setPlaylist(playList);
    //4. 设置音量
    player->setVolume(20);

    ui->localPage->addMusicMusicPage(musicList);
    // 关联暂停播放的信号 用于切换图片
    connect(player,&QMediaPlayer::stateChanged,this,&StarMusic::onPlayStateChanged);

    // 播放列表的模式改变时的信号槽关联
    connect(playList,&QMediaPlaylist::playbackModeChanged,this,&StarMusic::onPlaybackModeChanged);

    connect(playList,&QMediaPlaylist::currentIndexChanged,this,&StarMusic::onCurrentIndexChanged);

    connect(player,&QMediaPlayer::durationChanged,this,&StarMusic::onDurationChanged);

    connect(player,&QMediaPlayer::positionChanged,this,&StarMusic::onPositionChanger);

    connect(player,&QMediaPlayer::metaDataAvailableChanged,this,&StarMusic::onMetaDataAvailableChanged);
}

QJsonArray StarMusic::randomPiction()
{
    // 随机推荐
    QVector<QString> vecImageName;
    vecImageName << "001.png" <<  "002.png" << "003.png" << "004.png" << "005.png" <<
                    "006.png" <<  "007.png" << "008.png" << "009.png" << "010.png" <<
                    "011.png" <<  "012.png" << "013.png" << "014.png" << "015.png" <<
                    "016.png" <<  "017.png" << "018.png" << "019.png" << "020.png" ;
    std::random_shuffle(vecImageName.begin(),vecImageName.end());
    // path:":/images/rec/" + vecImageName[i];
    // text:"推荐-001"
    QJsonArray objArray;
    for (int i = 1;i < vecImageName.size(); i++)
    {
        // 用json格式
        QJsonObject obj;
        obj.insert("path",":/images/rec/" + vecImageName[i]);
        // 拼接字符串
        QString strText = QString("推荐-%1").arg(i,3,10,QChar('0'));
        obj.insert("text",strText);
        objArray.append(obj);
    }
    return objArray;
}

void StarMusic::connectSignalAndSlots()
{
    // 关联btForm信号和处理该信号的槽函数
    connect(ui->Rec,&btForm::btClick,this,&StarMusic::onbtFormClick);
    connect(ui->audio,&btForm::btClick,this,&StarMusic::onbtFormClick);
    connect(ui->music,&btForm::btClick,this,&StarMusic::onbtFormClick);
    connect(ui->like,&btForm::btClick,this,&StarMusic::onbtFormClick);
    connect(ui->local,&btForm::btClick,this,&StarMusic::onbtFormClick);
    connect(ui->recent,&btForm::btClick,this,&StarMusic::onbtFormClick);

    // 收藏或不收藏处理
    connect(ui->localPage,&CommonPage::updateLikeMusic,this,&StarMusic::onUpdateLikeMusicAndPage);
    connect(ui->localPage,&CommonPage::updateLikeMusic,this,&StarMusic::onUpdateLikeMusicAndPage);
    connect(ui->recentPage,&CommonPage::updateLikeMusic,this,&StarMusic::onUpdateLikeMusicAndPage);
    // 先显示本地下载
    ui->local->FirstShow(true);
    ui->stackedWidget->setCurrentIndex(4);

    // 播放控制区的信号和槽函数关联
    connect(ui->Play,&QPushButton::clicked,this,&StarMusic::onPlayMusic);
    connect(ui->playUp,&QPushButton::clicked,this,&StarMusic::onPlayUpClicked);
    connect(ui->playDown,&QPushButton::clicked,this,&StarMusic::onPlayDownClicked);
    connect(ui->playMode,&QPushButton::clicked,this,&StarMusic::onPlaybackModelClicked);

    // 三个页面播放全部音乐
    connect(ui->likePage,&CommonPage::playAll,this,&StarMusic::onPlayAll);
    connect(ui->localPage,&CommonPage::playAll,this,&StarMusic::onPlayAll);
    connect(ui->recentPage,&CommonPage::playAll,this,&StarMusic::onPlayAll);

    // 处理双击播放音乐
    connect(ui->likePage,&CommonPage::playMusicByIndex,this,&StarMusic::playMusicByIndex);
    connect(ui->localPage,&CommonPage::playMusicByIndex,this,&StarMusic::playMusicByIndex);
    connect(ui->recentPage,&CommonPage::playMusicByIndex,this,&StarMusic::playMusicByIndex);

    // 音量
    connect(volumetool,&VolumeTool::setMusicMuted,this,&StarMusic::setPlayerMuted);
    connect(volumetool,&VolumeTool::setMusicVolume,this,&StarMusic::setPlayerVolume);
    connect(ui->processBar,&MusicSlider::setMusicSliderPosition,this,&StarMusic::onMusicSliderChanged);

    // 显示满屏歌词
    connect(ui->lcdWord,&QPushButton::clicked,this,&StarMusic::onLrcWordClicked);
}

void StarMusic::initSqlite()
{
    // 数据库驱动加载
    QSqlDatabase sqlite = QSqlDatabase::addDatabase("QSQLITE");
    // 设置数据库名称
    sqlite.setDatabaseName("StarMusic.db");
    // 打开数据库
    if(!sqlite.open())
    {
        QMessageBox::critical(this,"StarMusic","数据库打开失败！");
        return;
    }
    // 创建表
    qDebug() << "数据库连接成功";
    QString sql = "CREATE TABLE IF NOT EXISTS MusicInfo(\
                    id INTEGER PRIMARY KEY AUTOINCREMENT,\
                    musicId varchar(50) UNIQUE,\
                    musicName varchar(50),\
                    musicSinger varchar(50),\
                    albumName varchar(50),\
                    musicUrl varchar(256),\
                    duration BIGINT,\
                    isLike INTEGER,\
                    isHistory INTEGER)";
    QSqlQuery query;
    if(!query.exec(sql))
    {
        QMessageBox::critical(this,"StarMusic","初始化错误");
        return;
    }
    qDebug() << "表格创建成功";
}

void StarMusic::initMusicList()
{
    musicList.readFromDB();

    ui->likePage->setMusicListType(PageType::LIKE_PAGE);
    ui->likePage->reFresh(musicList);
    ui->localPage->setMusicListType(PageType::LOCAL_PAGE);
    ui->localPage->reFresh(musicList);
    ui->recentPage->setMusicListType(PageType::HISTORY_PAGE);
    ui->recentPage->reFresh(musicList);

}

void StarMusic::updateBtformAnimal()
{
       // 获取currentPage的索引、
    int index = ui->stackedWidget->indexOf(currentPage);
    if(-1 == index)
    {
        qDebug()<<"该页面不存在";
        return;
    }
    QList<btForm*> btforms = this->findChildren<btForm*>();
    for (auto btForm : btforms)
    {
        if(btForm->getPageId() == index)
        {
            // 符合 则启动该页面动画
            btForm->FirstShow(true);
        }
        else
        {
            btForm->FirstShow(false);
        }
    }
}

void StarMusic::starMusicQuit()
{
    qDebug()<<"关闭前写入数据库";
    // 关闭前将数据写入数据库
    musicList.writeToDB();

    // 断开与数据库的连接
    sqlite.close();
    close();
}



void StarMusic::on_quit_clicked()
{    
    // 隐藏到托盘
    hide();
}

void StarMusic::onbtFormClick(int pageId)
{
    // 用户点击后 检测所有btForm控件，遍历一边 如果不是发送的控件 则背景颜色换回灰色
    QList<btForm*> btFormList = this->findChildren<btForm*>();
    for (auto btf : btFormList)
    {
        if(btf->getPageId() != pageId)
        {
            btf->clearBackground();
        }
    }
    isDrag = false;

    ui->stackedWidget->setCurrentIndex(pageId);
}

void StarMusic::mouseMoveEvent(QMouseEvent *event)
{
    if(Qt::LeftButton == event->buttons() && isDrag)
    {
        QPoint endPos = event->globalPos();
        move(endPos - m_offs);
        return;
    }
    //如果不是按下鼠标左键的情况，则调用父类的mouseMoveEvent函数
    QWidget::mouseMoveEvent(event);
}

void StarMusic::mousePressEvent(QMouseEvent *event)
{
    isDrag = true;
    if(event->button() == Qt::LeftButton)
    {
        QPoint startPos = event->globalPos();
        m_offs = startPos - frameGeometry().topLeft();
        return;
    }
    //如果不是按下鼠标左键的情况，则调用父类的mousePressEvent函数，
    QWidget::mousePressEvent(event);
}

void StarMusic::on_volume_clicked()
{
    // 先获取音量键的位置 转换为全局坐标
    QPoint point = ui->volume->mapToGlobal(QPoint(0,0));
    // 计算出具体要显示的位置
    QPoint volumeLeftTop = point - QPoint(volumetool->width()/2,volumetool->height());
    volumeLeftTop.setX(volumeLeftTop.x() + 15);
    volumeLeftTop.setY(volumeLeftTop.y() + 30);
    // 移动
    volumetool->move(volumeLeftTop);
    // 显示
    volumetool->show();

}

void StarMusic::on_addLocal_clicked()
{
    QFileDialog fileDialog(this);

    // 设置窗口的标题
    fileDialog.setWindowTitle("添加本地下载音乐");

    // 设置文件对话框默认的打开路径
    QDir dir(QDir::currentPath());
    dir.cdUp();
    QString projectPath = dir.path();
    projectPath += "/starmusic";
    fileDialog.setDirectory(projectPath);

    // 设置一次可打开多个
    fileDialog.setFileMode(QFileDialog::ExistingFiles);

    // 过滤
    QStringList mimeTypeFilters;
    mimeTypeFilters << "application/octet-stream";
    fileDialog.setMimeTypeFilters(mimeTypeFilters);

    if(QDialog::Accepted == fileDialog.exec())
    {
        // 点击了之后要切换页面 从commonpage切换到本地下载的页面

        // 获取所选中的文件信息
        QList<QUrl> fileUrls = fileDialog.selectedUrls();
        // 填充到本地下载页面

        // 将所有音乐添加到音乐列表中 管理解析后的Music对象
        musicList.AddMusicByUrl(fileUrls);

        // 将歌曲信息更新到CommonPage页面的控件中
        ui->stackedWidget->setCurrentIndex(4);
        ui->localPage->reFresh(musicList);

        // 将localpage上的歌曲添加到媒体播放列表中
        ui->localPage->addMusicToPlayList(musicList,playList);
    }

}

void StarMusic::onLrcWordClicked()
{
    lrcPage->show();
    lrcPageAnimal->start();
}

void StarMusic::onUpdateLikeMusicAndPage(bool isLike, const QString &musicId)
{
    // 修改状态
    auto it = musicList.findMusicByMusicId(musicId);
    if(it != musicList.end())
    {
        it->setIsLike(isLike);
    }

    // 更新page的歌曲列表信息
    ui->likePage->reFresh(musicList);
    ui->localPage->reFresh(musicList);
    ui->recentPage->reFresh(musicList);
}

// 与播放控制相关
void StarMusic::onPlayMusic()
{
    if(QMediaPlayer::PlayingState == player->state())
    {
        player->pause();
        //ui->Play->setIcon(QIcon(":/images/play3.png"));
    }
    else if(QMediaPlayer::PausedState == player->state())
    {
        player->play();
        //ui->Play->setIcon(QIcon(":/images/play_on.png"));
    }
    else if(QMediaPlayer::StoppedState == player->state())
    {
        player->play();
        //ui->Play->setIcon(QIcon(":/images/play_on.png"));
    }
    else
    {
        qDebug() << player->errorString();
    }
}

void StarMusic::onPlayStateChanged()
{
    if(player->state() == QMediaPlayer::PlayingState)
    {
        ui->Play->setIcon(QIcon(":/images/play_on.png"));
    }
    else
    {
        ui->Play->setIcon(QIcon(":/images/play3.png"));
    }
}

void StarMusic::onPlayUpClicked()
{
    playList->previous();
}

void StarMusic::onPlayDownClicked()
{
    playList->next();
}

void StarMusic::onPlaybackModelClicked()
{
    //根据当前播放模式 切换到下一个播放模式
    //设置提示
    // 列表循环 随机播放 单曲循环
    if(playList->playbackMode() == QMediaPlaylist::Loop)
    {
        // 随机播放
        playList->setPlaybackMode(QMediaPlaylist::Random);
        ui->playMode->setToolTip("随机播放");
    }
    else if(playList->playbackMode() == QMediaPlaylist::Random)
    {
        // 单曲循环
        playList->setPlaybackMode(QMediaPlaylist::CurrentItemInLoop);
        ui->playMode->setToolTip("单曲循环");
    }
    else if(playList->playbackMode() == QMediaPlaylist::CurrentItemInLoop)
    {
        // 列表循环
        playList->setPlaybackMode(QMediaPlaylist::Loop);
        ui->playMode->setToolTip("列表循环");
    }
    else
    {
        // 暂不支持
        qDebug() << "暂不支持";
    }
}

void StarMusic::onPlaybackModeChanged(QMediaPlaylist::PlaybackMode playbackMode)
{
    if(playbackMode == QMediaPlaylist::Loop)
    {
        ui->playMode->setIcon(QIcon(":/images/list_play.png"));
    }
    else if(playbackMode == QMediaPlaylist::Random)
    {
        ui->playMode->setIcon(QIcon(":/images/shuffle_2.png"));
    }
    else if(playbackMode == QMediaPlaylist::CurrentItemInLoop)
    {
        ui->playMode->setIcon(QIcon(":/images/single_play.png"));
    }
    else
    {
        qDebug() << "暂不支持";
    }
}

void StarMusic::onCurrentIndexChanged(int index)
{
    currentIndex = index;
    QString musicId = currentPage->getMusicIdByIndex(index);
    auto it = musicList.findMusicByMusicId(musicId);
    if(it != musicList.end())
    {
        it->setIsHistory(true);
    }
    ui->recentPage->reFresh(musicList);
}

void StarMusic::onPlayAll(PageType pagetype)
{
    // 播放对应页面的所有歌曲 默认从第0首开始播放
    CommonPage* page = ui->localPage;
    switch(pagetype)
    {
    case LIKE_PAGE:
        page = ui->likePage;
        break;
    case LOCAL_PAGE:
        page = ui->localPage;
        break;
    case HISTORY_PAGE:
        page = ui->recentPage;
        break;
    default:
        qDebug() << "暂时不支持";
        break;
    }

    // 已经确定要全部播放的页面
    playAllMusicOfCommonPage(page,0);
}

void StarMusic::playAllMusicOfCommonPage(CommonPage *page, int index)
{
     currentPage = page;
     updateBtformAnimal();
    // 清空之前的playlist中的歌曲
    playList->clear();
    // 添加到要播放的page页面中的所有歌曲
    page->addMusicToPlayList(musicList,playList);
    // 从第0首开始播放
    playList->setCurrentIndex(index);
    player->play();

}

void StarMusic::playMusicByIndex(CommonPage *page, int index)
{
    playAllMusicOfCommonPage(page,index);
}

void StarMusic::setPlayerMuted(bool isMuted)
{
    player->setMuted(isMuted);
}

void StarMusic::setPlayerVolume(int volume)
{
    player->setVolume(volume);
}

void StarMusic::onDurationChanged(qint64 duration)
{
    totalTime = duration;
    // 需要转换
    ui->endTime->setText(QString("%1:%2").arg(duration/1000/60,2,10,QChar('0'))
                         .arg(duration/1000%60,2,10,QChar('0')));
}

void StarMusic::onPositionChanger(qint64 position)
{
    ui->currentTime->setText(QString("%1:%2").arg(position/1000/60,2,10,QChar('0'))
                             .arg(position/1000%60,2,10,QChar('0')));
    // 更新进度条
    ui->processBar->setStep(position/(float)totalTime);
    // 满屏歌词显示
    lrcPage->showLrcWordLine(position);
}

void StarMusic::onMusicSliderChanged(float ration)
{
    // 根据传回的信号更新播放时间
    qint64 duration = totalTime * ration;
    ui->currentTime->setText(QString("%1:%2").arg(duration/1000/60,2,10,QChar('0'))
                             .arg(duration/1000%60,2,10,QChar('0')));
    player->setPosition(duration);

}

void StarMusic::onMetaDataAvailableChanged(bool available)
{
    //  歌曲名称
    //  歌手名称
    QString musicId = currentPage->getMusicIdByIndex(currentIndex);
    auto it = musicList.findMusicByMusicId(musicId);
    QString musicName("未知歌曲");
    QString musicSinger("歌手未知");
    if(it != musicList.end())
    {
        // 获取歌曲名称
        musicName = it->getMusicName();
        musicSinger = it->getMusicSinger();
    }
    ui->musicName->setText(musicName);
    ui->musicSinger->setText(musicSinger);
    QVariant image = player->metaData("ThumbnailImage");
    if(image.isValid())
    {
        QImage displayImage = image.value<QImage>();
        ui->musicCover->setPixmap(QPixmap::fromImage(displayImage));
        currentPage->setMusicImage(QPixmap::fromImage(displayImage));
    }
    else
    {
        qDebug() << "没有图片";
        // 默认图片
        QString path = ":/images/rec/001.png";
        ui->musicCover->setPixmap(path);
        currentPage->setMusicImage(path);
    }
     ui->musicCover->setScaledContents(true); // 图像自动伸缩 保证填满
     // 解析歌曲的歌词
     if(it != musicList.end())
     {
         QString lrcPath = it->getLrcFilePath();
         lrcPage->parseLrcFile(lrcPath);
     }

}



void StarMusic::on_min_clicked()
{
    // 最小化
    showMinimized();
}

void StarMusic::on_skin_clicked()
{
    // 换肤

    // 更换背景颜色或图片
    QMessageBox::information(this,"温馨提示","抱歉 换肤功能正在完善中");
}

void StarMusic::on_max_clicked()
{


}
